package com.tender.predicate;

import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.BeforeRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * @see BeforeRoutePredicateFactory 可以依据这个，依葫芦画瓢
 * 自定义会员等级
 */
@Component
public class CustomRoutePredicateFactory extends AbstractRoutePredicateFactory<CustomRoutePredicateFactory.Config> {

    public CustomRoutePredicateFactory() {
        super(Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userLevel");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return serverWebExchange -> {
            // 请求参数中要带有 userLevel 参数
            // http://localhost:9093/backend/service?userLevel=gold
            String userLevel = serverWebExchange.getRequest().getQueryParams().getFirst("userLevel");
            if (userLevel == null) {
                return false;
            }
            return userLevel.equalsIgnoreCase(config.getUserLevel());
        };
    }

    @Getter
    @Setter
    @Validated
    public static class Config {
        /**
         * yaml 中配置的 Custom=gold， gold 会赋值给 `userLevel` 字段
         */
        @NotNull
        private String userLevel;
    }

}
